package com.atguigu.cer;

import java.io.FileInputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-23
 */
public class CertificateDemo {


    /**
     * 读取 cer 文件, 本质上还是一个文本文件
     */
    public static void readCerFile() throws Exception {
        /* 取出证书--从文件中取出 */
        String certPath = "cer/public-rsa.cer";
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        FileInputStream in1 = new FileInputStream(certPath);
        Certificate c = cf.generateCertificate(in1);
        X509Certificate x509Certificate = (X509Certificate) c;

        // JAVA程序中显示证书指定信息
        System.out.println("输出证书信息:" + c.toString());
        System.out.println("版本号:" +  x509Certificate.getVersion());
        System.out.println("序列号:" +  x509Certificate.getSerialNumber().toString(16));
        System.out.println("主体名:" +  x509Certificate.getSubjectDN());
        System.out.println("签发者:" +  x509Certificate.getIssuerDN());
        System.out.println("有效期:" +  x509Certificate.getNotBefore());
        System.out.println("签名算法:"+ x509Certificate.getSigAlgName());
        byte[] sig = x509Certificate.getSignature();//签名值
        System.out.println("签名值：" + Arrays.toString(sig));
        PublicKey pk = x509Certificate.getPublicKey();
        byte[] pkEncoded = pk.getEncoded();
        System.out.println("公钥");
        for (byte b : pkEncoded){            System.out.print(b + ",");}


    }

    /**读取 p12 文件, 这个是二进制文件;  com/atguigu/cer/20060400001168004.p12
     * */
    private static void readPrivateFile( ) {

        URL url = CertificateDemo.class.getClassLoader().getResource("cer/20060400001168004.p12");  //直接获取 classLoader 下的文件 路径
       // final String keystore_file = "cer/20060400001168004.p12";
        final String keystorePassword = "111111";
        final String KEYSTORE_ALIAS = "alias";

        try {
            assert url != null;
            FileInputStream fis = new FileInputStream(url.getFile());

            // If the keystore password is empty(""), then we have to set
            // to null, otherwise it won't work!!!
            char[] nPassword ;
            if ((keystorePassword == null) || keystorePassword.trim().equals("")) {
                nPassword = null;
            } else {
                nPassword = keystorePassword.toCharArray();
            }
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            keyStore.load(fis, nPassword);  //密钥库 获取文件流
            fis.close();

            System.out.println("密钥存储类型 keystore type=" + keyStore.getType());

            Enumeration enumeration =  keyStore.aliases();
            String keyAlias = null;
            if ( enumeration.hasMoreElements()) // we are read in just one certificate.
            {
                keyAlias = (String) enumeration.nextElement();
                System.out.println("alias=[" + keyAlias + "]");
            }

            // Now once we know the alias, we could get the keys.
            System.out.println("is key entry=" + keyStore.isKeyEntry(keyAlias));
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, nPassword);
            Certificate cert = keyStore.getCertificate(keyAlias);
            PublicKey publicKey = cert.getPublicKey();

            System.out.println("证书类型 cert class = " + cert.getClass().getName());
            System.out.println("cert = " + cert);
            System.out.println("公钥 public key = "  + publicKey);
            System.out.println("私钥 private key = " + privateKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

        readPrivateFile();
    }

    // 192.168.32.1
    //192.168.32.128
}
